﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Groovy_IM.Assets;
using System.Threading;

namespace Groovy_IM
{
    public partial class ChatPage : PhoneApplicationPage
    {
        private int MsgID;

        private Timer m_Scroll;

        public ChatPage()
        {
            InitializeComponent();

            m_Scroll = new Timer(new TimerCallback(Scroll), null, 500, 500);
        }

        private void Scroll(object state)
        {
            Dispatcher.BeginInvoke(() =>
            {
                roomText.ScrollIntoView(roomText.Items[roomText.Items.Count - 1]);
            });
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string msg = "";

            if (NavigationContext.QueryString.TryGetValue("MsgID", out msg))
            {
                MsgID = int.Parse(msg);

                this.roomText.DataContext = App.Chats[0][MsgID].mViewModel;

                this.peopleList.DataContext = App.Chats[0][MsgID].pViewModel;
            }
        }

        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            if ((e.Orientation & PageOrientation.Portrait) == (PageOrientation.Portrait))
            {
                roomWidth.Width = 455;
                roomText.Width = 455;
                roomSend.Width = 455;
            }
            else
            {
                roomWidth.Width = 775;
                roomText.Width = 775;
                roomSend.Width = 775;
            }
        }
        
        private void mnuClearRoom_Click(object sender, EventArgs e)
        {
            App.Chats[0][MsgID].mViewModel.Items.Clear();
        }

        private void mnuClose_Click(object sender, EventArgs e)
        {
            App.m_Actions.CloseChat(App.Chats[0][MsgID].Account, MsgID);            
            App.Chats[0].Remove(App.Chats[0][MsgID]);
            NavigationService.GoBack();
        }

        private void send_Message_Click(object sender, EventArgs e)
        {
            App.m_Actions.SendChat(App.Chats[0][MsgID].Account, MsgID, roomSend.Text);

            roomSend.Text = "";
        }

        private void sendIM(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SendIMPage.xaml", UriKind.Relative));
        }

        private void help(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
        }

        private void inviteContact(object sender, EventArgs e)
        {
            inviteContactCanvas.Visibility = Visibility.Visible;
        }

        private void inviteContact_Click(object sender, RoutedEventArgs e)
        {
            inviteContactCanvas.Visibility = Visibility.Visible;
        }

        private void sendIM_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SendIMPage.xaml?User=" + (sender as MenuItem).Tag.ToString(), UriKind.Relative));
        }

        private void viewProfile_Click(object sender, RoutedEventArgs e)
        {
            App.m_Actions.RequestProfile(MsgID, (sender as MenuItem).Tag.ToString());
        }

        private void pivSwitch_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            updateButtonMnu(0, null, null, false, null);
            updateMenuMnu(0, null, false, null);
            updateButtonMnu(0, null, null, false, null);
            updateMenuMnu(0, null, false, null);
            updateButtonMnu(0, null, null, false, null);
            updateMenuMnu(0, null, false, null);
            updateButtonMnu(0, null, null, false, null);
            updateMenuMnu(0, null, false, null);
            
            switch (pivSwitch.SelectedIndex)
            {
                case 0:
                    updateButtonMnu(0, "/Images/App/AppBar/Chat.png", "send", true, new EventHandler(send_Message_Click));
                    updateMenuMnu(0, "clear", true, new EventHandler(mnuClearRoom_Click));
                    updateMenuMnu(1, "close", true, new EventHandler(mnuClose_Click));
                    updateMenuMnu(2, "invite contact", true, new EventHandler(inviteContact));  
                    break;
                case 1:
                    updateButtonMnu(0, "/Images/App/AppBar/IM.png", "send", true, new EventHandler(sendIM));
                    updateMenuMnu(0, "close", true, new EventHandler(mnuClose_Click));
                    updateMenuMnu(1, "help", true, new EventHandler(help));
                    updateMenuMnu(2, "invite contact", true, new EventHandler(inviteContact));                    
                    break;
            }
        }
        
        private void updateButtonMnu(int Index, string uriString, string Text, bool Visibile, EventHandler Handler)
        {
            ApplicationBarIconButton button = null;

            if (ApplicationBar.Buttons.Count > Index)
            {
                button = ApplicationBar.Buttons[Index] as ApplicationBarIconButton;
            }

            if (button != null)
            {
                {
                    ApplicationBar.Buttons.Remove(button);
                }
            }

            if (Visibile == true)
            {
                button = new ApplicationBarIconButton(new Uri(uriString, UriKind.Relative));
                button.Text = Text;
                button.Click += Handler;
                ApplicationBar.Buttons.Insert(Index, button);
            }
        }

        private void updateMenuMnu(int Index, string Text, bool Visibile, EventHandler Handler)
        {
            ApplicationBarMenuItem menu = null;

            if (ApplicationBar.MenuItems.Count > Index)
            {
                menu = ApplicationBar.MenuItems[Index] as ApplicationBarMenuItem;
            }

            if (menu != null)
            {
                {
                    ApplicationBar.MenuItems.Remove(menu);
                }
            }

            if (Visibile == true)
            {
                menu = new ApplicationBarMenuItem(Text);
                menu.Text = Text;
                menu.Click += Handler;
                ApplicationBar.MenuItems.Insert(Index, menu);
            }
        }

        private void Invite_Click(object sender, RoutedEventArgs e)
        {
            if (contact.Text.Length < 1)
            {
                MessageBox.Show("You must enter a contacts name to invite them.");
                return;
            }

            App.m_Actions.RequestInvite(App.Chats[0][MsgID].Account, MsgID, contact.Text, invMsg.Text);
            contact.Text = "";
            invMsg.Text = "Come Join Me!";
            inviteContactCanvas.Visibility = Visibility.Collapsed;
        }

        private void Border_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SendIMPage.xaml", UriKind.Relative));
            App.m_Actions.Vibrate(100);
        }

        private void Border_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.m_Actions.Vibrate(100);
        }

        private void roomText_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            var sView = e.ManipulationContainer as ScrollViewer;

            double lBox = 25 - sView.ScrollableHeight;

            double nBox = 25 - sView.VerticalOffset;

            if (lBox < nBox)
                m_Scroll.Dispose();
            else
                m_Scroll = new Timer(new TimerCallback(Scroll), null, 500, 500);
        }

        private void invMsg_GotFocus(object sender, RoutedEventArgs e)
        {
            if (invMsg.Text == "Come Join Me!")
                invMsg.Text = "";
        }

        private void invMsg_LostFocus(object sender, RoutedEventArgs e)
        {
            if (invMsg.Text == "")
                invMsg.Text = "Come Join Me!";
        }

    }
}